import { NextRequest, NextResponse } from "next/server";
import fs from "fs";
import path from "path";
import { promises as fsPromises } from "fs";
import Papa from "papaparse";

export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    const grade = searchParams.get("grade");
    const recent = searchParams.get("recent") === "true";
    const showInternational = searchParams.get("int") === "true";
    
    const workingDir = process.cwd();
    const csvDir = path.join(workingDir, "data", "csv");
    
    // 确保目录存在
    try {
      await fsPromises.access(csvDir);
    } catch (error) {
      // 目录不存在，创建它
      await fsPromises.mkdir(csvDir, { recursive: true });
      
      // 返回空数据
      return NextResponse.json({ exams: [] });
    }
    
    // 获取所有的CSV文件
    const files = await fsPromises.readdir(csvDir);
    
    // 根据int参数过滤CSV文件
    let csvFiles;
    if (showInternational) {
      // 仅返回[INT]开头的文件（国际考试）
      csvFiles = files.filter(file => file.startsWith("[INT]") && file.endsWith(".csv"));
    } else {
      // 跳过[INT]开头的文件（不显示国际考试）
      csvFiles = files.filter(file => !file.startsWith("[INT]") && file.endsWith(".csv"));
    }
    
    if (csvFiles.length === 0) {
      return NextResponse.json({ exams: [] });
    }
    
    // 读取并解析所有CSV文件
    const allExams: any[] = [];
    
    for (const file of csvFiles) {
      const filePath = path.join(csvDir, file);
      const fileContent = await fsPromises.readFile(filePath, "utf-8");
      
      // 使用PapaParse解析CSV
      const { data, errors } = Papa.parse(fileContent, {
        header: true,
        skipEmptyLines: true,
        transformHeader: (header) => header.trim(),
        transform: (value) => {
          // 保留原始格式，确保"+"不被转换
          return value.trim();
        }
      });
      
      if (errors.length > 0) {
        console.error(`解析文件 ${file} 时出错:`, errors);
        continue;
      }
      
      // 添加源文件信息并过滤
      const examsWithSource = data.map((exam: any) => ({
        ...exam,
        source: file
      }));
      
      // 如果指定了年级，则进行过滤
      const filteredExams = grade
        ? examsWithSource.filter((exam: any) => exam.年级 === grade)
        : examsWithSource;
      
      allExams.push(...filteredExams);
    }
    
    // 如果请求最近的考试，则按日期过滤
    if (recent) {
      // 不再限制只返回过去3天的考试
      // 直接返回所有考试数据，由前端根据用户选择的日期范围(3天/7天/本月)进行过滤
      return NextResponse.json({ exams: allExams });
    }
    
    return NextResponse.json({ exams: allExams });
  } catch (error) {
    console.error("处理考试数据请求时出错:", error);
    return NextResponse.json({ error: "处理请求时出错" }, { status: 500 });
  }
}